{% extends "web/chat/base.html" %}

{% block content %}
  <textarea  id="chat-log" disabled rows="20"></textarea><br/>
  <input  id="chat-message-input" type="text"/><br/>
  <input  id="chat-message-submit" type="button" value="Send"/>
{% endblock %}

{% block js %}
<script>
  {#$('#page_header').text('聊天室');#}
  {#$('#page_header_descript').text('chat room');#}

  var chatSocket = new WebSocket(
    'ws://' + window.location.host + '/chat/ws/');

  chatSocket.onmessage = function(e) {
    var data = JSON.parse(e.data);
    var message = data['message'];
    document.querySelector('#chat-log').value += (message + '\n');
  };

  chatSocket.onopen = function (e){
      console.log('connect ws')
  }

  chatSocket.onclose = function(e) {
    console.error('Chat socket closed unexpectedly');
  };

  document.querySelector('#chat-message-input').focus();
  document.querySelector('#chat-message-input').onkeyup = function(e) {
    if (e.keyCode === 13) {  // enter, return
        document.querySelector('#chat-message-submit').click();
    }
  };

  document.querySelector('#chat-message-submit').onclick = function(e) {
    var messageInputDom = document.querySelector('#chat-message-input');
    var message = messageInputDom.value;
    let stringifyMsg = JSON.stringify({
        'message': message
    });
      console.log(stringifyMsg)
    chatSocket.send(stringifyMsg);

    messageInputDom.value = '';
  };
</script>
{% endblock %}